package com.wjc.wjc.web;


import com.wjc.wjc.service.StudentService;
import com.wjc.wjc.service.UserService;
import com.wjc.wjc.unity.Student;
import com.wjc.wjc.unity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private StudentService studentService;
    @Autowired
    private UserService userService;

    @GetMapping("/")
    public String first(){
        return "login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        @RequestParam String option,
                        HttpSession session,
                        RedirectAttributes attributes){

        if(option.equals("0")){
            String sno=username;
            Student student=studentService.login(sno,password);
            if (student!=null){
                student.setPassword(null);
                session.setAttribute("student",student);
                return "index";
            }else {
                attributes.addFlashAttribute("message","用户名密码错误");
                return "redirect:/";
            }
        }else {
            User user=userService.login(username,password);
            if (user!=null){
                user.setPassword(null);
                session.setAttribute("user",user);
                return "admin/index";
            }
            attributes.addFlashAttribute("message","用户名密码错误");
            return "redirect:/";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("student");
        session.removeAttribute("user");
        return "redirect:/";
    }
}
